package com.jianshuge.app.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jianshuge.app.AppConfig;
import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;

import com.jianshuge.app.bean.BookItem;
import com.jianshuge.app.bean.BookItemList;
import com.jianshuge.app.bean.Notice;
import com.jianshuge.app.bean.MyResult;
import com.jianshuge.app.bean.MyBooklistDetail;
import com.jianshuge.app.bean.MyBooklistDetail.MyBooklistItem;
import com.jianshuge.app.adapter.ListViewBookAdapter;
import com.jianshuge.app.adapter.ListViewMyBooklistItemAdapter;

import com.jianshuge.app.common.FileUtils;
import com.jianshuge.app.common.StringUtils;
import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.widget.PullToRefreshListView;

import com.jianshuge.zxing.activity.CaptureActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class BooklistDetail extends BaseActivity {
	
	private ImageView mBack;
	private ImageView mRefresh;
	private ProgressBar mProgressbar;
	
	private LinearLayout mLinearlayout;
	////////////////////////////////////////////////////
	private PullToRefreshListView mLvMyBooklistItem;
	private ListViewMyBooklistItemAdapter lvMyBooklistItemAdapter;
	private List<MyBooklistItem> lvMyBooklistItemData = new ArrayList<MyBooklistItem>();
	
	private View lvMyBooklistItem_footer;
	private TextView lvMyBooklistItem_foot_more;
	private ProgressBar lvMyBooklistItem_foot_progress;
	
    private Handler mMyBooklistItemHandler;
    private int lvSumData;
    ////////////////////////////////////////////////////////
    
    private ImageView userface;
    private TextView username;
    private TextView content;
    private TextView edit_booklist;
    
    private TextView client;
    private TextView date;
    private TextView commentCount;

    private Handler mHandler;
    private MyBooklistDetail my_booklist_detail;
    private List<MyBooklistItem> my_booklistitem_list;
    private int cur_booklist_id;
	private int curCatalog;	
	private int curLvDataState;
	private ProgressDialog mProgress;
	
	public InputMethodManager imm;
	///////////////////////////////////////////////
	private ViewSwitcher mFootViewSwitcher;
	private EditText mFootEditer;
	private Button mFootPubcomment;
//	private String tempCommentKey = AppConfig.TEMP_COMMENT;	
	private int cur_booklistitem_id = 0;
	/////////////////////////////////////////////
	private Button mFootScanBarcode;
	private RadioButton mShare;
	private RadioButton mFollowBL;
	
	private int cur_login_uid;
	private ListView mlvSearchBook;
	private List<BookItem> lvSearchBookData = new ArrayList<BookItem>();	
	private ListViewBookAdapter lvSearchBookAdapter;
	private View lvSearchBook_footer;
	private TextView lvSearchBook_foot_more;
	private ProgressBar lvSearchBook_foot_progress;
    private Handler mSearchBookHandler;
    private int lvSearchBookSumData;
    
	private Button mSearchBtn;
	private EditText mSearchEditer;
	private ProgressBar mSearchProgressbar;
	private String curSearchContent = "";
	
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.booklist_detail);
        
        this.initView();
        this.initData();   
        this.initSearchBookListView();
        this.initSearchData();
    }
    
    /**
     * 头部加载展示
     * @param type
     * @param action 1-init 2-refresh
     */
    private void headButtonSwitch(int type,int action) {
    	switch (type) {
		case DATA_LOAD_ING:
			if(action==1)mLinearlayout.setVisibility(View.GONE);
			mProgressbar.setVisibility(View.VISIBLE);
			mRefresh.setVisibility(View.GONE);
			break;
		case DATA_LOAD_COMPLETE:
			mLinearlayout.setVisibility(View.VISIBLE);
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		}
    }
    
    private void searchheadButtonSwitch(int type) {
    	switch (type) {
    	case DATA_LOAD_ING:
    		mSearchBtn.setClickable(false);
    		mSearchProgressbar.setVisibility(View.VISIBLE);
			break;
		case DATA_LOAD_COMPLETE:
			mSearchBtn.setClickable(true);
			mSearchProgressbar.setVisibility(View.GONE);
			break;
		}
    }
	
    
    //初始化视图控件
    private void initView()
    {    	
		cur_booklist_id = getIntent().getIntExtra("booklist_id", 0);
		curCatalog = 1;
		
		final AppContext ac = (AppContext)getApplication();
		cur_login_uid = ac.getLoginUid();
    	
    	mBack = (ImageView)findViewById(R.id.booklist_detail_back);
    	mRefresh = (ImageView)findViewById(R.id.booklist_detail_refresh);
    	mProgressbar = (ProgressBar)findViewById(R.id.booklist_detail_head_progress);    	
       	mLinearlayout = (LinearLayout)findViewById(R.id.booklist_detail_linearlayout);

    	mBack.setOnClickListener(UIHelper.finish(this));
    	mRefresh.setOnClickListener(refreshClickListener);    	
    	imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	
    	/////////////////////////////////////////////////////////////////////////////////////////
    	mFootViewSwitcher = (ViewSwitcher)findViewById(R.id.booklist_detail_foot_viewswitcher);
    	mFootPubcomment = (Button)findViewById(R.id.booklist_detail_foot_pubcomment);
    	mFootPubcomment.setOnClickListener(commentpubClickListener);
//    	if(cur_booklist_id > 0) tempCommentKey = AppConfig.TEMP_COMMENT + "_" + curCatalog + "_" + cur_booklist_id;
    	
    	mFootEditer = (EditText)findViewById(R.id.booklist_detail_foot_editer);
    	mFootEditer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//显示软键盘&隐藏表情
				showIMM(true);
			}
		});
    	
    	mFootEditer.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if(mFootViewSwitcher.getDisplayedChild()==1){
						mFootViewSwitcher.setDisplayedChild(0);
						mFootEditer.clearFocus();//隐藏软键盘
						mFootEditer.setVisibility(View.GONE);//隐藏编辑框
						showIMM(false);
					}
					return true;
				}
				return false;
			}
		});
		
    	/***
    	mFootEditebox = (ImageView)findViewById(R.id.booklist_detail_footbar_editebox);
    	mFootEditebox.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mFootViewSwitcher.showNext();
				mFootEditer.setVisibility(View.VISIBLE);
				mFootEditer.requestFocus();
				mFootEditer.requestFocusFromTouch();
				imm.showSoftInput(mFootEditer, 0);//显示软键盘
			}
		});
		***/
		
    	/***
    	mFootEditer.addTextChangedListener(UIHelper.getTextWatcher(this, tempCommentKey));
    	UIHelper.showTempEditContent(this, mFootEditer, tempCommentKey);
    	***/
    	
    	///////////////////////////////////////////////////////////////////////////////////////
    	mFootScanBarcode = (Button)findViewById(R.id.booklist_detail_footbar_scanbarcode);   
    	mFootScanBarcode.setOnClickListener( new View.OnClickListener() {
			public void onClick(View v) {					
				Intent openCameraIntent = new Intent(v.getContext(), CaptureActivity.class );
				openCameraIntent.putExtra("booklist_id", cur_booklist_id);
				startActivityForResult(openCameraIntent, UIHelper.REQUEST_CODE_FOR_RESULT);
			}
		});
    	mFollowBL = (RadioButton)findViewById(R.id.booklist_detail_footbar_follow);
    	mFollowBL.setOnClickListener(followClickListener);
		mShare = (RadioButton)findViewById(R.id.booklist_detail_footbar_share);
		mShare.setOnClickListener(shareClickListener);
    	///////////////////////////////////////////////////////////////////////////////////////


    	
    	userface = (ImageView)findViewById(R.id.booklist_content_listitem_userface);
    	username = (TextView)findViewById(R.id.booklist_content_listitem_username);
    	content = (TextView)findViewById(R.id.booklist_content_listitem_title);
    	edit_booklist = (TextView)findViewById(R.id.booklist_content_listitem_edit_booklist);
    	edit_booklist.setOnClickListener(editbooklistClickListener);

//    	client = (TextView)findViewById(R.id.booklist_content_listitem_client);
    	
    	date = (TextView)findViewById(R.id.booklist_content_listitem_date);
    	commentCount = (TextView)findViewById(R.id.booklist_content_listitem_commentCount);
    	
        ////////////////////////////////////////////////////////////
        lvMyBooklistItem_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvMyBooklistItem_foot_more = (TextView)lvMyBooklistItem_footer.findViewById(R.id.listview_foot_more);
        lvMyBooklistItem_foot_progress = (ProgressBar)lvMyBooklistItem_footer.findViewById(R.id.listview_foot_progress);
       
    	lvMyBooklistItemAdapter = new ListViewMyBooklistItemAdapter(this, lvMyBooklistItemData, R.layout.booklist_detail_listitem, cur_booklist_id); 
    	mLvMyBooklistItem = (PullToRefreshListView)findViewById(R.id.booklist_detail_bookitems);
        mLvMyBooklistItem.addFooterView(lvMyBooklistItem_footer);
        mLvMyBooklistItem.setAdapter(lvMyBooklistItemAdapter); 
        
        mLvMyBooklistItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		//点击头部、底部栏无效
        		if(position == 0 || view == lvMyBooklistItem_footer) 
        			return;
        		
        		MyBooklistItem my_booklist_item = null;
        		//判断是否是TextView
        		if(view instanceof TextView){
        			my_booklist_item = (MyBooklistItem)view.getTag();
        		}else{
            		ImageView img = (ImageView)view.findViewById(R.id.bookitem_listitem_book_image);
            		my_booklist_item = (MyBooklistItem)img.getTag();
        		} 
        		if(my_booklist_item == null) return;        		
        		
        		UIHelper.showBookDetail(BooklistDetail.this, my_booklist_item.book_id);
        	}
		});
        
        mLvMyBooklistItem.setOnScrollListener(new AbsListView.OnScrollListener() {
 			public void onScrollStateChanged(AbsListView view, int scrollState) {
 				mLvMyBooklistItem.onScrollStateChanged(view, scrollState);
 				
 				//数据为空--不用继续下面代码了
 				if(lvMyBooklistItemData.size() == 0) return;
 				
 				//判断是否滚动到底部
 				boolean scrollEnd = false;
 				try {
 					if(view.getPositionForView(lvMyBooklistItem_footer) == view.getLastVisiblePosition())
 						scrollEnd = true;
 				} catch (Exception e) {
 					scrollEnd = false;
 				}
 				
 				if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
 				{
 					mLvMyBooklistItem.setTag(UIHelper.LISTVIEW_DATA_LOADING);
 					lvMyBooklistItem_foot_more.setText(R.string.load_ing);
 					lvMyBooklistItem_foot_progress.setVisibility(View.VISIBLE);
 					
 					//当前pageIndex
 					int pageIndex = lvSumData/20;
 					loadLvMyBooklistItemData(cur_booklist_id, curCatalog, pageIndex, mMyBooklistItemHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
 				}
 			}
 			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
 				mLvMyBooklistItem.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
        });
        
        mLvMyBooklistItem.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        	
        	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				//点击头部、底部栏无效
        		if(position == 0 || view == lvMyBooklistItem_footer) 
        			return false;
				
        		MyBooklistItem my_booklist_item = null;
        		//判断是否是TextView
        		if(view instanceof TextView){
        			my_booklist_item = (MyBooklistItem)view.getTag();
        		}else{
            		ImageView img = (ImageView)view.findViewById(R.id.bookitem_listitem_book_image);
            		my_booklist_item = (MyBooklistItem)img.getTag();
        		} 
        		if(my_booklist_item == null) 
        			return false;
        		
        		final MyBooklistItem item = my_booklist_item;
        		final AppContext ac = (AppContext)getApplication();
				//操作--回复 & 删除
        		int uid = ac.getLoginUid();
        		//判断该评论是否是当前登录用户发表的：true--有删除操作  false--没有删除操作
        		if(uid == my_booklist_item.user_id )
        		{
	        		final Handler handler = new Handler(){
						public void handleMessage(Message msg) {
							if(msg.what == 1){
								MyResult res = (MyResult)msg.obj;
								if(res.OK()){
									lvSumData--;
									lvMyBooklistItemData.remove(item);
									lvMyBooklistItemAdapter.notifyDataSetChanged();
								}
								UIHelper.ToastMessage(BooklistDetail.this, res.getErrorMessage());
							}else{
								((AppException)msg.obj).makeToast(BooklistDetail.this);
							}
						}        			
	        		};
	        		final Thread thread = new Thread(){
	        			/***
	        			public void run() {
							Message msg = new Message();
							try {
								Result res = ac.delComment(curId, curCatalog, item.id, item.user_id );
								msg.what = 1;
								msg.obj = res;
				            } catch (AppException e) {
				            	e.printStackTrace();
				            	msg.what = -1;
				            	msg.obj = e;
				            }
				            
			                handler.sendMessage(msg);
						} 
						***/       			
	        		};
	        	//	UIHelper.showCommentOptionDialog(BooklistDetail.this, curId, curCatalog, item, thread);
        		}
        		else
        		{
        			//UIHelper.showCommentOptionDialog(BooklistDetail.this, curId, curCatalog, item, null);
        		}
				return true;
			}        	
		});
        
        mLvMyBooklistItem.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				loadLvMyBooklistItemData(cur_booklist_id, curCatalog, 1, mMyBooklistItemHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
            }
        });
        
        ///////////////////////////////////////////////////////////////////////////////
    	mSearchBtn = (Button)findViewById(R.id.search_douban_book_btn);
    	mSearchEditer = (EditText)findViewById(R.id.search_douban_book_editer);
    	mSearchProgressbar = (ProgressBar)findViewById(R.id.search_douban_book_progress);
    	
    	mSearchBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				mSearchEditer.clearFocus();
				curSearchContent = mSearchEditer.getText().toString();
				loadLvSearchBookData(1, 0, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_INIT);
				
			}
		});
    	
    	mSearchEditer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){  
					imm.showSoftInput(v, 0);  
		        }  
		        else{  
		            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
		        }  
			}
		});
    	
    	mSearchEditer.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH) {
					if(v.getTag() == null) {
						v.setTag(1);
						mSearchEditer.clearFocus();
						curSearchContent = mSearchEditer.getText().toString();
						
						loadLvSearchBookData(1, 0, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_INIT);
						
					}else{
						v.setTag(null);
					}
					return true;
				}
				return false;
			}
		});
    	
    }
    
	

    
    //初始化控件数据
  	private void initSearchData() 
  	{			

		mSearchBookHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				searchheadButtonSwitch(DATA_LOAD_COMPLETE);

				if(msg.what >= 0){						
					BookItemList list = (BookItemList)msg.obj;
					Notice notice = list.getNotice();
					
					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSearchBookSumData = msg.what;
						lvSearchBookData.clear();//先清除原有数据
						lvSearchBookData.addAll(list.getBookList());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvSearchBookSumData += msg.what;
						if(lvSearchBookData.size() > 0){
							for(BookItem bookitem1 : list.getBookList()){
								boolean b = false;
								for(BookItem bookitem2 : lvSearchBookData){
									if(bookitem1.getId() == bookitem2.getId()){
										b = true;
										break;
									}
								}
								if(!b) lvSearchBookData.add(bookitem1);
							}
						}else{
							lvSearchBookData.addAll(list.getBookList());
						}
						break;
					}	
					
					if(msg.what < 10){
						mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_FULL);
						lvSearchBookAdapter.notifyDataSetChanged();
						lvSearchBook_foot_more.setText(R.string.load_full);
					}else if(msg.what == 10){					
						mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_MORE);
						lvSearchBookAdapter.notifyDataSetChanged();
						lvSearchBook_foot_more.setText(R.string.load_more);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_MORE);
					lvSearchBook_foot_more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(BooklistDetail.this);
				}
				if(lvSearchBookData.size()==0){
					mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					lvSearchBook_foot_more.setText(R.string.load_empty);
				}
				lvSearchBook_foot_progress.setVisibility(View.GONE);
				if(msg.arg1 != UIHelper.LISTVIEW_ACTION_SCROLL){
					mlvSearchBook.setSelection(0);//返回头部
				}
			}
		};
		
  	}
  	
    private void initSearchBookListView() {
    	
    	lvSearchBook_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvSearchBook_foot_more = (TextView)lvSearchBook_footer.findViewById(R.id.listview_foot_more);
    	lvSearchBook_foot_progress = (ProgressBar)lvSearchBook_footer.findViewById(R.id.listview_foot_progress);
    	
    	lvSearchBookAdapter = new ListViewBookAdapter(this, lvSearchBookData, R.layout.book_listitem); 
    	
    	mlvSearchBook = (ListView)findViewById(R.id.search_doubanbook_listview);
    	mlvSearchBook.setVisibility(ListView.GONE);
    	mlvSearchBook.addFooterView(lvSearchBook_footer);
    	mlvSearchBook.setAdapter(lvSearchBookAdapter); 
    	
    	mlvSearchBook.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		//点击底部栏无效
        		if( view == lvSearchBook_footer ) 
        			return;
        		
        		BookItem book_item = null;
        		//判断是否是TextView
        		if(view instanceof TextView){
        			book_item = (BookItem)view.getTag();
        		}else{
        			TextView title = (TextView)view.findViewById(R.id.book_listitem_title);
        			book_item = (BookItem)title.getTag();
        		} 
        		
        		if(book_item == null) 
        			return;
         		
         		mlvSearchBook.setVisibility(ListView.GONE);
         		//lvSearchBookData.clear();
        		mLinearlayout.setVisibility(View.VISIBLE);
        		UIHelper.showAddBookResult(BooklistDetail.this, book_item.getSubjectId(), cur_booklist_id);
        	}
		});
    	
    	mlvSearchBook.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {				
				//数据为空--不用继续下面代码了
				if(lvSearchBookData.size() == 0) return;
				
				//判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if(view.getPositionForView(lvSearchBook_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int curLvDataState = StringUtils.toInt(mlvSearchBook.getTag());
				if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
				{
					mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvSearchBook_foot_more.setText(R.string.load_ing);
					lvSearchBook_foot_progress.setVisibility(View.VISIBLE);
					//当前pageIndex
					int pageIndex = lvSearchBookSumData / 10;
					loadLvSearchBookData(1, pageIndex, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				
			}
		});
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) return;   
    	if (data == null) return;
        if (requestCode == UIHelper.REQUEST_CODE_FOR_RESULT) 
        {
			loadBooklistDetail(cur_booklist_id, mHandler, true);
			loadLvMyBooklistItemData(cur_booklist_id,curCatalog,0,mMyBooklistItemHandler,UIHelper.LISTVIEW_ACTION_REFRESH);
			
			/***
        	Comment comm = (Comment)data.getSerializableExtra("COMMENT_SERIALIZABLE");
        	lvCommentData.add(0, comm);
        	lvCommentAdapter.notifyDataSetChanged();
        	mLvComment.setSelection(0);
        	***/
        }
	}
    
	private void loadLvSearchBookData(final int catalog,final int pageIndex,final Handler handler,final int action){  
		
		if(StringUtils.isEmpty(curSearchContent)){
			UIHelper.ToastMessage(BooklistDetail.this, "请输入搜索内容");
			return;
		}
		
		searchheadButtonSwitch(DATA_LOAD_ING);
		mLinearlayout.setVisibility(View.GONE);
		mlvSearchBook.setVisibility(ListView.VISIBLE);
		
		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					BookItemList book_item_list = ((AppContext)getApplication()).SearchDouban(catalog, curSearchContent, pageIndex, 10);
					msg.what = book_item_list.getPageSize();
					msg.obj = book_item_list;
	            } catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
				msg.arg1 = action;//告知handler当前action
				handler.sendMessage(msg);
			}
		}.start();
	} 
	
	private View.OnClickListener searchBtnClick(final Button btn,final int catalog){
    	return new View.OnClickListener() {
			public void onClick(View v) {
				//开始搜索
				mSearchEditer.clearFocus();
				curSearchContent = mSearchEditer.getText().toString();
				loadLvSearchBookData(1, 0, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
		    	
			}
		};
    }
	
    
    /**
     * 线程加载书单条目数据
     * @param id 当前书单id
     * @param catalog 分类
     * @param pageIndex 当前页数
     * @param handler 处理器
     * @param action 动作标识
     */
	private void loadLvMyBooklistItemData(final int booklist_id, final int catalog, final int pageIndex,final Handler handler, final int action){  
		
		this.headButtonSwitch(DATA_LOAD_ING,2);
		
		new Thread(){
			public void run() {
				
				Message msg = new Message();
				boolean isRefresh = false;
				if(action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				
				try {
					
					/***
					my_booklistitem_list = my_booklist_detail.getMyBooklistItems();				
					if( my_booklistitem_list.isEmpty() ) 
					{
						my_booklist_detail = ((AppContext)getApplication()).getBooklistDetail(booklist_id, isRefresh);
						my_booklistitem_list.addAll(my_booklist_detail.getMyBooklistItems());
					}
					***/
					my_booklistitem_list = ((AppContext)getApplication()).getBooklistDetail(booklist_id, isRefresh).getMyBooklistItems();
					
					msg.what = my_booklistitem_list.size();
					msg.obj = my_booklistitem_list;
	            } catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
				msg.arg1 = action;//告知handler当前action
                handler.sendMessage(msg);
			}
		}.start();
	} 
	
    
    //初始化控件数据
	private void initData()
	{		
 		
    	mHandler = new Handler(){ 
    		
    		public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE,1);
				
				if(msg.what == 1){
					
					String faceURL = my_booklist_detail.getUserAvatar();
					if(faceURL.endsWith("portrait.gif") || StringUtils.isEmpty(faceURL)) {
						userface.setImageResource(R.drawable.widget_dface);
					}else{
						UIHelper.showUserFace(userface, faceURL);
					}
					userface.setOnClickListener(faceClickListener);
					userface.setTag(my_booklist_detail);
	
					username.setText(my_booklist_detail.getUserName());
					content.setText(my_booklist_detail.getTitle());

			    //	client.setText("来自: Android");
			    	date.setText(StringUtils.friendly_time(my_booklist_detail.getUpdateTime()));
				//	commentCount.setText(my_booklist_detail.getCommentsCount()+"回|" + my_booklist_detail.getViewsCount() + "阅");
					commentCount.setText("  " + my_booklist_detail.getViewsCount() + "阅");
					
					if( my_booklist_detail.getUserId() == cur_login_uid )
						edit_booklist.setVisibility(View.VISIBLE);
					
					
					final AppContext ac = (AppContext)getApplication();
					if( my_booklist_detail.getUserId() == ac.getLoginUid() ) {
						mFollowBL.setText("返回");
					}
					else
					{
						if (my_booklist_detail.getFollowStatus() == true) {
							mFollowBL.setText("已关注");
						} else {	
							mFollowBL.setText("关注书单");
						}
					}
					
					
					//发送通知广播
					if(msg.obj != null){
						UIHelper.sendBroadCast(BooklistDetail.this, (Notice)msg.obj);
					}
				}else if(msg.what == 0){
					UIHelper.ToastMessage(BooklistDetail.this, R.string.msg_load_is_null);	
				}else{
					((AppException)msg.obj).makeToast(BooklistDetail.this);
				}
    		}
		};
		
    	this.loadBooklistDetail(cur_booklist_id, mHandler, true);
    	
       	//加载书单条目
    	mMyBooklistItemHandler = new Handler() 	{
    		
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE,2);
				
				if(msg.what >= 0){
					
					List<MyBooklistItem> list =( ArrayList<MyBooklistItem> )msg.obj;
					//处理listview数据
					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
						lvSumData = msg.what;
						lvMyBooklistItemData.clear();//先清除原有数据
						lvMyBooklistItemData.addAll(list);
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvSumData += msg.what;
						if(lvMyBooklistItemData.size() > 0){
							for(MyBooklistItem my_booklist_item1 : list){
								boolean b = false;
								for(MyBooklistItem my_booklist_item2 : lvMyBooklistItemData){
									if(my_booklist_item1.id == my_booklist_item2.id ){
										b = true;
										break;
									}
								}
								if(!b) lvMyBooklistItemData.add(my_booklist_item1);
							}
						}else{
							lvMyBooklistItemData.addAll(list);
						}
						break;
					}	
					
					
					if(msg.what < 20){
						curLvDataState = UIHelper.LISTVIEW_DATA_FULL;
						lvMyBooklistItemAdapter.notifyDataSetChanged();
						lvMyBooklistItem_foot_more.setText(R.string.load_full);
					}else if(msg.what == 20){					
						curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
						lvMyBooklistItemAdapter.notifyDataSetChanged();
						lvMyBooklistItem_foot_more.setText(R.string.load_more);
					}
					

				}				
				else if(msg.what == -1){
					//有异常--也显示更多 & 弹出错误消息
					curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
					lvMyBooklistItem_foot_more.setText(R.string.load_more);
					((AppException)msg.obj).makeToast(BooklistDetail.this);
				}
				
				if(lvMyBooklistItemData.size()==0){
					curLvDataState = UIHelper.LISTVIEW_DATA_EMPTY;
					lvMyBooklistItem_foot_more.setText(R.string.load_empty);
				}
				
				lvMyBooklistItem_foot_progress.setVisibility(View.GONE);
				if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH)
					mLvMyBooklistItem.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
			}
		};
		
		this.loadLvMyBooklistItemData(cur_booklist_id, curCatalog, 1, mMyBooklistItemHandler, UIHelper.LISTVIEW_ACTION_INIT);

	}
	
	/**
	 * 线程加载书单详情数据
	 * @param tweetId
	 * @param handler
	 */
	private void loadBooklistDetail(final int booklist_id, final Handler handler, final boolean isRefresh) {
		
		this.headButtonSwitch(DATA_LOAD_ING,1);
		
		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					my_booklist_detail = ((AppContext)getApplication()).getBooklistDetail(booklist_id, isRefresh);
					msg.what = (my_booklist_detail!=null && my_booklist_detail.getId()>0) ? 1 : 0;
					msg.obj = (my_booklist_detail!=null) ? my_booklist_detail.getNotice() : null;
				} catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
		
	}
	
	private View.OnClickListener shareClickListener = new View.OnClickListener() {
		public void onClick(View v) {

			String share_title = "荐书阁 好书推荐：" + my_booklist_detail.getTitle() + "（分享自 @荐书阁）";
			String share_url = "http://jianshuge.com/booklist/show/" + my_booklist_detail.getId() + ".html";
			
			if(lvMyBooklistItemData.size() > 0){
				for(MyBooklistItem my_booklist_item : my_booklistitem_list){
					
					String share_img_url = my_booklist_item.book_image_url;
					final String filename = FileUtils.getFileName(share_img_url);
					String filepath = v.getContext().getFilesDir() + File.separator + filename;	
					
					if( FileUtils.checkFilePathExists(filepath) )
						UIHelper.showShareDialog(BooklistDetail.this, share_title, share_url, filepath);
					else
						UIHelper.showShareDialog(BooklistDetail.this, share_title, share_url, null);
					
					break;
				}
			} else {
				
				UIHelper.showShareDialog(BooklistDetail.this, share_title, share_url, null);
			}

			
			
		}
	};
	
	private View.OnClickListener followClickListener = new View.OnClickListener() {
		public void onClick(View v) {

			if (cur_booklist_id == 0 || my_booklist_detail == null) {
				return;
			}
			
			final AppContext ac = (AppContext) getApplication();
			final int uid = ac.getLoginUid();
			if( my_booklist_detail.getUserId() == uid ) {
				((BooklistDetail)v.getContext()).finish();
				return;
			}

			mProgress = ProgressDialog.show(v.getContext(), null, "关注中···",true,true); 
			
			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mProgress!=null)
						mProgress.dismiss();
					
					if (msg.what == 1) {
						MyResult res = (MyResult) msg.obj;
						
						if (res.OK()) {
							
							if (my_booklist_detail.getFollowStatus() == true) {
								my_booklist_detail.setFollowStatus(false);
								mFollowBL.setText("关注书单");
							} else {	
								my_booklist_detail.setFollowStatus(true);
								mFollowBL.setText("已关注");
							}
							
							// 重新保存缓存
							ac.saveObject(my_booklist_detail, my_booklist_detail.getCacheKey());
							
						}
					
						UIHelper.ToastMessage(BooklistDetail.this, res.getErrorMessage());
					
					} else {					
						((AppException) msg.obj).makeToast(BooklistDetail.this);
					}
				}
			};
			
			new Thread() {
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {
						if (my_booklist_detail.getFollowStatus() == true) {
							res = ac.unfollowBooklist(uid, cur_booklist_id);
						} else {
							res = ac.followBooklist(uid, cur_booklist_id);
						}
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			}.start();

		}
		
	};
	
    private void showIMM( boolean show_im ) {
    	showOrHideIMM( show_im  );
    }

    private void showOrHideIMM( boolean show_im ) {
    	if(show_im  == false){
			//隐藏软键盘
			imm.hideSoftInputFromWindow(mFootEditer.getWindowToken(), 0);
		}else{
			//显示软键盘
			imm.showSoftInput(mFootEditer, 0);
		}
    }
    
    private View.OnClickListener editbooklistClickListener = new View.OnClickListener() {
 		public void onClick(View v) {	
 			UIHelper.showBooklistEdit(BooklistDetail.this, cur_booklist_id, content.getText().toString() ); 
 		}
 	};

    private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {	
			loadBooklistDetail(cur_booklist_id, mHandler, true);
			loadLvMyBooklistItemData(cur_booklist_id,curCatalog,0,mMyBooklistItemHandler,UIHelper.LISTVIEW_ACTION_REFRESH);
		}
	};
	
	private View.OnClickListener faceClickListener = new View.OnClickListener(){
		public void onClick(View v) {
			MyBooklistDetail my_bl_detail = (MyBooklistDetail)v.getTag();
			UIHelper.showUserCenter(v.getContext(), my_bl_detail.getUserId(), my_bl_detail.getUserName());
		}
	};

	public void startPubComment(int booklistitem_id) {
		cur_booklistitem_id = booklistitem_id;

		if(mFootViewSwitcher.getDisplayedChild() == 0){
		
			mFootViewSwitcher.showNext();
			mFootEditer.setVisibility(View.VISIBLE);
			mFootEditer.requestFocus();
			mFootEditer.requestFocusFromTouch();
			imm.showSoftInput(mFootEditer, 0);//显示软键盘
		}
	}
	
	private View.OnClickListener commentpubClickListener = new View.OnClickListener() {
		public void onClick(View v) {	
			
			if(cur_booklistitem_id == 0){
				return;
			}
			
			final String comment_content = mFootEditer.getText().toString();
			if(StringUtils.isEmpty(comment_content)){
				UIHelper.ToastMessage(v.getContext(), "请输入评论内容");
				return;
			}
			
			final AppContext ac = (AppContext)getApplication();
			
			mProgress = ProgressDialog.show(v.getContext(), null, "发布中···",true,true); 
			
			final Handler handler = new Handler(){
				public void handleMessage(Message msg) {
					
					if(mProgress!=null)
						mProgress.dismiss();
					
					if(msg.what == 1 && msg.obj != null){
						MyResult res = (MyResult)msg.obj;
						UIHelper.ToastMessage(BooklistDetail.this, res.getErrorMessage());
						if(res.OK()){

							//恢复初始底部栏
							mFootViewSwitcher.setDisplayedChild(0);
							mFootEditer.clearFocus();
							mFootEditer.setText("");
							mFootEditer.setVisibility(View.GONE);
							//隐藏软键盘
							imm.hideSoftInputFromWindow(mFootEditer.getWindowToken(), 0);
						}

						loadLvMyBooklistItemData(cur_booklist_id,curCatalog,0,mMyBooklistItemHandler,UIHelper.LISTVIEW_ACTION_REFRESH);

					}
					else {
						((AppException)msg.obj).makeToast(BooklistDetail.this);
					}
				}
			};
			
			new Thread(){
				
				public void run() {
					Message msg = new Message();
					MyResult res = new MyResult();
					try {
						//发表评论
						res = ac.pubComment(cur_login_uid, cur_booklistitem_id, comment_content, 1);
						msg.what = 1;
						msg.obj = res;
		            } catch (AppException e) {
		            	e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
		            }
					handler.sendMessage(msg);
				}
			}.start();
			
		}
	
	};
	
	public void removeComment( final int uid, final int rid, final int booklistitem_id) {
		
		final AppContext ac = (AppContext)getApplication();
			
		mProgress = ProgressDialog.show(this, null, "移除中···",true,true); 
			
		final Handler handler = new Handler(){
			public void handleMessage(Message msg) {
					
				if(mProgress!=null)
					mProgress.dismiss();
					
				if(msg.what == 1 && msg.obj != null){
					MyResult res = (MyResult)msg.obj;
					UIHelper.ToastMessage(BooklistDetail.this, res.getErrorMessage());
					if(res.OK()){
							//恢复初始底部栏
						mFootViewSwitcher.setDisplayedChild(0);
						mFootEditer.clearFocus();
						mFootEditer.setText("");
						mFootEditer.setVisibility(View.GONE);
						//隐藏软键盘
						imm.hideSoftInputFromWindow(mFootEditer.getWindowToken(), 0);
					}

					loadLvMyBooklistItemData(cur_booklist_id, curCatalog, 0, mMyBooklistItemHandler,UIHelper.LISTVIEW_ACTION_REFRESH);

				}
				else {
					((AppException)msg.obj).makeToast(BooklistDetail.this);
				}
			}
		};
			
		new Thread(){
				
			public void run() {
				Message msg = new Message();
				MyResult res = new MyResult();
				try {
					//发表评论
					res = ac.delComment(uid, rid, booklistitem_id);
					msg.what = 1;
					msg.obj = res;
	            } catch (AppException e) {
	            	e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
	            }
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	public void favoriteBook( final MyBooklistItem my_booklist_item  ) {
		
		if ( my_booklist_item == null ) {
			return;
		}
		
		mProgress = ProgressDialog.show(this, null, "收藏中···",true,true); 

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				
				if(mProgress!=null)
					mProgress.dismiss();
					
				if(msg.what == 1 && msg.obj != null){
					
					MyResult res = (MyResult) msg.obj;
					UIHelper.ToastMessage(BooklistDetail.this, res.getErrorMessage());
					if (res.OK()) {
						
					//	loadLvMyBooklistItemData(cur_booklist_id,curCatalog,0,mMyBooklistItemHandler,UIHelper.LISTVIEW_ACTION_REFRESH);
					
					} else {					
						
						((AppException)msg.obj).makeToast(BooklistDetail.this);
					}
				}
			}
		};
			
		new Thread() {
			public void run() {
				Message msg = new Message();
				MyResult res = null;
				try {
					final AppContext ac = (AppContext)getApplication();
					final int uid = ac.getLoginUid();
					res = ac.addFavorite(uid, my_booklist_item.book_id);
					
					
					
					msg.what = 1;
					msg.obj = res;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	};
	
	
	public void voteBook( final MyBooklistItem my_booklist_item ) {
			
		mProgress = ProgressDialog.show(this, null, "加载中···",true,true); 

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				
				if(mProgress!=null)
					mProgress.dismiss();
			
				if(msg.what == 1 && msg.obj != null) {
					
					MyResult res = (MyResult) msg.obj;
					UIHelper.ToastMessage(BooklistDetail.this, res.getErrorMessage());		
					if (res.OK()) {
						loadLvMyBooklistItemData(cur_booklist_id, curCatalog, 0, mMyBooklistItemHandler,UIHelper.LISTVIEW_ACTION_REFRESH);	
					} else {					
						((AppException) msg.obj).makeToast( BooklistDetail.this );
					}
				}	
			}
		};
			
		new Thread() {
			public void run() {
				Message msg = new Message();
				MyResult res = null;
				try {

					//AppContext ac = (AppContext)context.getApplicationContext();
					final AppContext ac = (AppContext)getApplication();
					final int uid = ac.getLoginUid();
					res = ac.addVote( uid, my_booklist_item.id, cur_booklist_id,  my_booklist_item.book_id, my_booklist_item.user_id);						
					msg.what = 1;
					msg.obj = res;
					
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	};	
}